/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
    let res = null
    let pVal = p.val
    let qVal = q.val
    function recursion(node) {
        let left = null;
        let right = null;
        let val = node.val

        if (node.left) {
            left = recursion(node.left)
        }
        if (node.right) {
            right = recursion(node.right)
        }

        let arr = [left, right, val]

        if (arr.includes(pVal) && arr.includes(qVal)) {
            res = node
        }

        if (val === pVal || val === qVal) {
            return val
        }
        if (left !== null) return left;
        if (right !== null) return right;
        return null
    }
    recursion(root)
    return res
};


